package com.view.subOperation;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeSelectionModel;

import com.dto.CourseDTO;
import com.dto.TeachDTO;
import com.dto.TeacherDTO;
import com.service.Course;
import com.service.Teach;
import com.util.tool.NodeValue;
import com.util.tool.WindowUtil;

/**
 * 添加课程信息（教师添加题库状态情况前，只能添加该老师的授课的题库情况，即相应的一对一关系）
 * 
 * @author yachao
 *
 */
@SuppressWarnings("serial")
public class LinkCourse extends JDialog {

	private static LinkCourse linkCourse;
	private JTree courseTree;
	private DefaultTreeModel courseModel;
	private JTable courseTable;
	private DefaultTableModel tableModel;
	private JLabel L_link_num;
	private TeacherDTO teacherDTO;
	private CourseDTO courseDTO;
	private int clickCount = -1;

	private final JPanel contentPanel = new JPanel();

	public static void main(String[] args) {
		try {
			LinkCourse dialog = new LinkCourse();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public LinkCourse() {
		setTitle("教师模式>>管理课程");
		setBounds(100, 100, 705, 408);
		setLocation(WindowUtil.setLocation(new Dimension(this.getWidth(), this
				.getHeight())));
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);

		JSplitPane splitPane = new JSplitPane();
		splitPane.setBounds(0, 0, 689, 337);
		contentPanel.add(splitPane);

		courseTree = new JTree();
		courseTree.setFont(new Font("华文楷体", Font.BOLD, 14));
		showTree();
		courseTree.addTreeSelectionListener(new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				do_valueChanged_action(e);
			}
		});
		splitPane.setLeftComponent(courseTree);
		splitPane.setDividerLocation(120);
		splitPane.setDividerSize(5);

		JPanel containsPane = new JPanel();
		splitPane.setRightComponent(containsPane);
		containsPane.setLayout(null);

		JPanel selectedPane = new JPanel();
		selectedPane.setBounds(0, 0, 533, 49);
		selectedPane.setLayout(null);
		containsPane.add(selectedPane);

		JLabel L_selected_tip = new JLabel("已关联课程：");
		L_selected_tip.setHorizontalAlignment(SwingConstants.CENTER);
		L_selected_tip.setFont(new Font("华文楷体", Font.BOLD, 16));
		L_selected_tip.setBounds(0, 0, 109, 49);
		selectedPane.add(L_selected_tip);

		L_link_num = new JLabel("0");
		L_link_num.setHorizontalAlignment(SwingConstants.CENTER);
		L_link_num.setFont(new Font("华文楷体", Font.BOLD, 16));
		L_link_num.setBounds(109, 0, 54, 49);
		selectedPane.add(L_link_num);

		JLabel L_tip = new JLabel("门");
		L_tip.setHorizontalAlignment(SwingConstants.CENTER);
		L_tip.setFont(new Font("华文楷体", Font.BOLD, 16));
		L_tip.setBounds(163, 0, 54, 49);
		selectedPane.add(L_tip);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(0, 49, 533, 286);
		containsPane.add(scrollPane);

		splitPane.setRightComponent(containsPane);
		splitPane.setDividerLocation(175);
		splitPane.setDividerSize(5);

		String[] headers = { "序号", "课程名", "教师名" };
		courseTable = new JTable();
		tableModel = new DefaultTableModel();
		tableModel.setColumnIdentifiers(headers);
		courseTable.setModel(tableModel);
		courseTable.setRowHeight(30);
		courseTable.setFont(new Font("华文楷体", Font.BOLD, 14));
		courseTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				clickCount = courseTable.getSelectedRow();
			}
		});
		setTableCellRenderer();

		scrollPane.setViewportView(courseTable);

		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{

				JButton okButton = new JButton("选择");
				okButton.setFont(new Font("华文楷体", Font.BOLD, 14));
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						do_ok_action(e);
					}
				});
				okButton.setActionCommand("选择");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);

				JButton btnSave = new JButton("保存");
				btnSave.setFont(new Font("华文楷体", Font.BOLD, 14));
				btnSave.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						do_save_action(e);
					}
				});
				btnSave.setActionCommand("选择");
				buttonPane.add(btnSave);
			}
			{
				JButton cancelButton = new JButton("退出");
				cancelButton.setFont(new Font("华文楷体", Font.BOLD, 14));
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						do_exit_action(e);
					}
				});

				JButton btnRemove = new JButton("取消关联");
				btnRemove.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						do_remove_action(e);
					}
				});

				JButton btnCancel = new JButton("移除");
				btnCancel.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						do_cancel_action(e);
					}
				});
				btnCancel.setFont(new Font("华文楷体", Font.BOLD, 14));
				btnCancel.setActionCommand("选择");
				buttonPane.add(btnCancel);
				btnRemove.setFont(new Font("华文楷体", Font.BOLD, 14));
				btnRemove.setActionCommand("选择");
				buttonPane.add(btnRemove);
				cancelButton.setActionCommand("退出");
				buttonPane.add(cancelButton);
			}
		}

		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				try {
					do_exit_action(null);
				} catch (Exception ex) {
					// 此处不再进行相应处理
				}
			}
		});
	}

	protected void do_cancel_action(ActionEvent e) {
		if (clickCount >= 0) {
			tableModel.removeRow(clickCount);

			int k = 0;
			for (int i = 0; i < tableModel.getRowCount(); i++) {
				tableModel.setValueAt(new Integer(++k), i, 0);
			}
			L_link_num.setText(tableModel.getRowCount() + ""); // 记录已关联课程数量
		} else {
			JOptionPane.showMessageDialog(null, "请先选择要移除的记录！");
		}
	}

	protected void do_remove_action(ActionEvent e) {
		if (clickCount >= 0) {
			int result = JOptionPane.showConfirmDialog(null, "确定取消关联？");

			if (result == JOptionPane.OK_OPTION) {
				CourseDTO course = (CourseDTO) tableModel.getValueAt(
						clickCount, 1);
				TeacherDTO teacher = (TeacherDTO) tableModel.getValueAt(
						clickCount, 2);

				boolean success = new Teach().removeLink(teacher.getT_id(),
						course.getC_id());
				if (success) {
					JOptionPane.showMessageDialog(null, "已取消关联!");
					loadData();
				} else {
					JOptionPane.showMessageDialog(null, "取消关联失败!");
				}
			} else {
				return;
			}
		} else {
			JOptionPane.showMessageDialog(null, "请先选择要取消关联的记录！");
		}
	}

	protected void do_save_action(ActionEvent e) {
		boolean success = true;
		StringBuilder builder = new StringBuilder();

		int rowCount = tableModel.getRowCount();
		int startCount = Integer.parseInt(L_link_num.getText().trim());

		if (tableModel.getRowCount() > 0) {
			for (int i = startCount; i < rowCount; i++) {
				CourseDTO course = (CourseDTO) tableModel.getValueAt(i, 1);
				TeacherDTO teacher = (TeacherDTO) tableModel.getValueAt(i, 2);
				TeachDTO teach = new TeachDTO(teacher.getT_id(),
						course.getC_id());
				success = new Teach().saveTeach(teach);

				if (!success) {
					builder.append(teach + ",");
				}
			}
			if (success) {
				JOptionPane.showMessageDialog(null, "保存成功!");
				L_link_num.setText(rowCount + "");
			} else {
				builder.append(";");
				JOptionPane.showMessageDialog(null, "保存失败！保存失败的信息为:" + builder);
			}
		} else {
			return;
		}
	}

	public void setTeacherDTO(TeacherDTO teacherDTO) {
		this.teacherDTO = teacherDTO;
		loadData();
	}

	private void setTableCellRenderer() {
		/* 设置表格数据居中显示 */
		DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
		renderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
		courseTable.setDefaultRenderer(Object.class, renderer);

		/* 设置列宽 */
		TableColumn tc_num = courseTable.getColumnModel().getColumn(0);
		tc_num.setPreferredWidth(1);
	}

	private void loadData() {
		try {
			/* 清空表中记录 */
			if (tableModel.getRowCount() > 0) {
				tableModel.setRowCount(0);
			}

			List<String> course_ids = new Teach().getCourseId(teacherDTO
					.getT_id());

			if (course_ids.size() > 0) {
				int k = 0;
				Vector<Object> v_link = null;

				for (int i = 0; i < course_ids.size(); i++) {
					v_link = new Vector<Object>();
					v_link.add(new Integer(++k)); // 序号
					CourseDTO course = new Course().getCourseById(course_ids
							.get(i));
					v_link.add(course);
					v_link.add(teacherDTO);
					tableModel.addRow(v_link);
				}
				L_link_num.setText(tableModel.getRowCount() + ""); // 记录已关联课程数量
			} else {
				return;
			}
		} catch (Exception ex) {
			// 此处不再进行相应处理
		}
	}

	protected void do_valueChanged_action(TreeSelectionEvent e) {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) courseTree
				.getLastSelectedPathComponent();

		if (node == null) {
			return;
		}

		courseDTO = (CourseDTO) ((NodeValue) node.getUserObject()).getObject();
	}

	private void showTree() {
		Course course_service = new Course();
		CourseDTO course = course_service.getCourseById("001");
		DefaultMutableTreeNode root = new DefaultMutableTreeNode(new NodeValue(
				course.getC_name(), course));

		List<CourseDTO> courses = course_service.getCourses();
		courses.remove(0);
		initCourseTree(courses, "001", root);

		courseModel = new DefaultTreeModel(root);
		courseTree.setModel(courseModel);
		courseTree.getSelectionModel().setSelectionMode(
				DefaultTreeSelectionModel.SINGLE_TREE_SELECTION);
	}

	private void initCourseTree(List<CourseDTO> courses, String support,
			DefaultMutableTreeNode parent) {
		try {
			for (int i = 0; i < courses.size(); i++) {
				CourseDTO course = courses.get(i);
				if (course.getSupport().equals(support)) {
					DefaultMutableTreeNode other = new DefaultMutableTreeNode(
							new NodeValue(course.getC_name(), course));
					// 不需要初始化叶子节点
					// initCourseTree(courses, course.getSupport(), other);
					parent.add(other);
				}
			}
		} catch (Exception ex) {
		}
	}

	protected void do_exit_action(ActionEvent e) {
		linkCourse = null;
		LinkCourse.this.dispose();
	}

	protected void do_ok_action(ActionEvent e) {
		if (courseDTO != null) {
			/* 先检测该课程是否已被选择过 */
			int count = tableModel.getRowCount();
			for (int i = 0; i < count; i++) {
				CourseDTO course = (CourseDTO) tableModel.getValueAt(i, 1);
				if (courseDTO.getC_name().equals(course.getC_name())) {
					JOptionPane.showMessageDialog(null, "该课程已被关联,不可重复选！");
					return;
				}
			}

			Vector<Object> v_result = new Vector<Object>();
			v_result.add(new Integer(tableModel.getRowCount() + 1)); // 序号
			v_result.add(courseDTO); // 课程名
			v_result.add(teacherDTO); // 教师名
			tableModel.addRow(v_result);
		} else {
			JOptionPane.showMessageDialog(null, "请先选择要关联的课程!");
		}
	}

	public static void display() {
		if (linkCourse == null) {
			linkCourse = new LinkCourse();
		}
		linkCourse.setVisible(true);
		linkCourse.setResizable(false);
	}

	public static LinkCourse getInstance() {
		if (linkCourse == null) {
			linkCourse = new LinkCourse();
		}
		return linkCourse;
	}
}
